'use strict'
import moment from 'moment'
import { get as getAliOssParams } from '@/api/oss/ali'

var OSS = require('ali-oss')

export default {

  /**
   * 创建随机字符串
   * @param num
   * @returns {string}
   */
  randomString(num) {
    const chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
    let res = ''
    for (let i = 0; i < num; i++) {
      var id = Math.ceil(Math.random() * 35)
      res += chars[id]
    }
    return res
  },

  /**
   * 创建oss客户端对象
   * @returns {*}
   */
  async createOssClient() {
    let res = await getAliOssParams()
    return new Promise((resolve, reject) => {
      const client = new OSS({
        region: 'oss-cn-beijing',
        bucket: 'tuotuo-dev',
        accessKeyId: res.data.accessKeyId,
        accessKeySecret: res.data.accessKeySecret,
        stsToken: res.data.securityToken,
      })
      resolve(client)
    })
  },
  /**
   * 文件上传
   * @param option 参考csdn: https://blog.csdn.net/qq_27626333/article/details/81463139
   */
  ossUploadFile(option, type) {
    const file = option.file
    const self = this
    return new Promise((resolve, reject) => {
      const date = moment(new Date()).format('YYYYMMDD') // 当前时间
      const dateTime = moment(new Date()).format('DDHHmmss') // 当前时间
      const randomStr = self.randomString(5)//  4位随机字符串
      const extensionName = file.name.substr(file.name.indexOf('.')) // 文件扩展名
      var fileName = ''
      switch (type) {
        case 'image':
          // fileName = 'images/' + date + '/' + dateTime + '_' + randomStr + extensionName
          fileName = process.env.VUE_APP_OSS_IMAGE + date + '/' + dateTime + '_' + randomStr + extensionName
          break;
        case 'files':
          fileName = process.env.VUE_APP_OSS_IMAGE + date + '/' + dateTime + '_' + randomStr + extensionName
          break;
      }
      // 执行上传
      self.createOssClient().then(client => {
        // 异步上传,返回数据
        // resolve({
        //   fileName: file.name,
        //   fileUrl: 'http://tuotuo-dev.oss-cn-beijing.aliyuncs.com/' + fileName
        // })
        resolve({
          data: 'http://tuotuo-dev.oss-cn-beijing.aliyuncs.com/' + fileName
        })
        // 上传处理
        // 整体上传文件
        client.put(fileName, file)

        // 分片上传文件
        // client.multipartUpload(fileName, file, {
        //   progress: function(p) {
        //     const e = {}
        //     e.percent = Math.floor(p * 100)
        //     // console.log('Progress: ' + p)
        //     option.onProgress(e)
        //   }
        // }).then((val) => {
        //   // console.info(val)
        //   if (val.res.statusCode === 200) {
        //     option.onSuccess(val)
        //     return val
        //   } else {
        //     option.onError('上传失败')
        //   }
        // }, err => {
        //   option.onError('上传失败')
        //   reject(err)
        // })
      })
    })
  },
  // 批量删除文件
  ossDeleteFiles(files) {
    this.createOssClient().then(client => {
      client.deleteMulti(files)
    })
  }
}
